package cn.yh.province.service.Impl;

import cn.yh.province.dao.Impl.ProvinceDaoImpl;
import cn.yh.province.dao.ProvinceDao;
import cn.yh.province.pojo.Province;
import cn.yh.province.service.ProvinceService;
import cn.yh.province.utils.JedisUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;

import java.util.List;

public class ProvinceServiceImpl  implements ProvinceService {

    private final ProvinceDao provinceDao = new ProvinceDaoImpl();
    @Override
    public List<Province> getAllProvinces() {
        return provinceDao.getAllProvince();
    }

    /**
     * 查询所有  加缓存
     * @return
     */
    @Override
    public String findJson() throws JsonProcessingException {
        //先从缓存中查  有则从缓存中取  没有则从数据库中取  然后放到缓存中
        Jedis jedis = JedisUtil.getJedis();
        String province = jedis.get("province");

        //缓存中有  则直接返回
        if (!StringUtils.isEmpty(province)){
            System.out.println("缓存中有内容，直接返回....");
            return province;
        }
        //从数据库中查询
        List<Province> allProvince = provinceDao.getAllProvince();
        //转成json数据
        ObjectMapper mapper = new ObjectMapper();
        String value = mapper.writeValueAsString(allProvince);
        //查到的数据再放入缓存中
        jedis.set("province",value);
        return value;
    }
}
